document.addEventListener('DOMContentLoaded', function() {
    // 画板页面管理
    const MAX_PAGES = 30;
    let pages = []; // 存储所有页面的画布数据
    let currentPageIndex = 0;
    
    // 获取画布和上下文
    const canvas = document.getElementById('whiteboard');
    const ctx = canvas.getContext('2d');
    
    // 获取分页相关元素
    const pageInfo = document.getElementById('pageInfo');
    const pagesList = document.getElementById('pagesList');
    const prevPageBtn = document.getElementById('prevPage');
    const nextPageBtn = document.getElementById('nextPage');
    const newPageBtn = document.getElementById('newPage');
    
    // 绘图状态变量
    let isDrawing = false;
    let lastX = 0;
    let lastY = 0;
    let mode = 'pencil'; // 默认为画笔模式
    let color = '#000000';
    let lineWidth = 5;
    
    // 每个页面都有自己的绘图历史
    function createNewPage() {
        return {
            drawingHistory: [],
            currentStep: -1
        };
    }
    
    // 初始化第一个页面
    pages.push(createNewPage());
    
    // 设置画布大小
    function resizeCanvas() {
        canvas.width = canvas.offsetWidth;
        canvas.height = canvas.offsetHeight;
        // 重绘画布
        redraw();
    }
    
    // 初始化时调整画布大小
    resizeCanvas();
    
    // 当窗口大小改变时调整画布大小
    window.addEventListener('resize', resizeCanvas);
    
    // 保存初始状态
    saveDrawingState();
    
    // 更新页面信息显示
    function updatePageInfo() {
        pageInfo.textContent = `第 ${currentPageIndex + 1} 页 / 共 ${pages.length} 页`;
        
        // 更新页面列表
        pagesList.innerHTML = '';
        pages.forEach((page, index) => {
            const li = document.createElement('li');
            li.textContent = `页面 ${index + 1}`;
            li.dataset.page = index;
            if (index === currentPageIndex) {
                li.classList.add('active');
            }
            li.addEventListener('click', () => {
                switchToPage(index);
            });
            pagesList.appendChild(li);
        });
        
        // 更新导航按钮状态
        prevPageBtn.disabled = currentPageIndex === 0;
        nextPageBtn.disabled = currentPageIndex === pages.length - 1;
        newPageBtn.disabled = pages.length >= MAX_PAGES;
    }
    
    // 切换到指定页面
    function switchToPage(pageIndex) {
        if (pageIndex < 0 || pageIndex >= pages.length) return;
        
        // 保存当前页面
        saveCurrentPage();
        
        // 切换页面
        currentPageIndex = pageIndex;
        loadCurrentPage();
        
        // 更新UI
        updatePageInfo();
    }
    
    // 保存当前页面数据
    function saveCurrentPage() {
        // 当前页面的最后一步如果不是当前画布状态，则保存当前状态
        const currentPage = pages[currentPageIndex];
        if (currentPage.drawingHistory.length === 0 || 
            currentPage.currentStep < currentPage.drawingHistory.length - 1) {
            saveDrawingState();
        }
    }
    
    // 加载当前页面数据
    function loadCurrentPage() {
        const currentPage = pages[currentPageIndex];
        if (currentPage.drawingHistory.length > 0 && currentPage.currentStep >= 0) {
            ctx.putImageData(currentPage.drawingHistory[currentPage.currentStep], 0, 0);
        } else {
            // 如果是新页面，清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }
    }
    
    // 创建新页面
    function createPage() {
        if (pages.length >= MAX_PAGES) return;
        
        // 保存当前页面
        saveCurrentPage();
        
        // 创建新页面
        pages.push(createNewPage());
        currentPageIndex = pages.length - 1;
        
        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 更新UI
        updatePageInfo();
    }
    
    // 分页控制事件
    prevPageBtn.addEventListener('click', () => {
        if (currentPageIndex > 0) {
            switchToPage(currentPageIndex - 1);
        }
    });
    
    nextPageBtn.addEventListener('click', () => {
        if (currentPageIndex < pages.length - 1) {
            switchToPage(currentPageIndex + 1);
        }
    });
    
    newPageBtn.addEventListener('click', createPage);
    
    // 事件监听器
    canvas.addEventListener('mousedown', startDrawing);
    canvas.addEventListener('mousemove', draw);
    canvas.addEventListener('mouseup', stopDrawing);
    canvas.addEventListener('mouseout', stopDrawing);
    
    // 触摸设备支持
    canvas.addEventListener('touchstart', handleTouchStart);
    canvas.addEventListener('touchmove', handleTouchMove);
    canvas.addEventListener('touchend', stopDrawing);
    
    // 工具按钮事件
    document.getElementById('pencil').addEventListener('click', function() {
        setMode('pencil');
    });
    
    document.getElementById('eraser').addEventListener('click', function() {
        setMode('eraser');
    });
    
    document.getElementById('clear').addEventListener('click', clearCanvas);
    
    document.getElementById('save').addEventListener('click', saveCanvas);
    
    // 颜色选择器
    document.getElementById('colorPicker').addEventListener('input', function(e) {
        color = e.target.value;
    });
    
    // 笔刷大小
    document.getElementById('brushSize').addEventListener('input', function(e) {
        lineWidth = e.target.value;
    });
    
    // 设置绘图模式
    function setMode(newMode) {
        mode = newMode;
        
        // 更新按钮活跃状态
        document.getElementById('pencil').classList.remove('active');
        document.getElementById('eraser').classList.remove('active');
        
        document.getElementById(mode).classList.add('active');
    }
    
    // 开始绘图
    function startDrawing(e) {
        isDrawing = true;
        
        const pos = getPosition(e);
        lastX = pos.x;
        lastY = pos.y;
    }
    
    // 绘图
    function draw(e) {
        if (!isDrawing) return;
        
        const pos = getPosition(e);
        
        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(pos.x, pos.y);
        
        // 根据模式设置样式
        if (mode === 'pencil') {
            ctx.strokeStyle = color;
            ctx.lineWidth = lineWidth;
        } else if (mode === 'eraser') {
            ctx.strokeStyle = '#ffffff';
            ctx.lineWidth = lineWidth * 2;
        }
        
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
        ctx.stroke();
        
        lastX = pos.x;
        lastY = pos.y;
    }
    
    // 停止绘图
    function stopDrawing() {
        if (isDrawing) {
            isDrawing = false;
            saveDrawingState();
        }
    }
    
    // 清空画布
    function clearCanvas() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        saveDrawingState();
    }
    
    // 保存画布内容
    function saveCanvas() {
        const dataURL = canvas.toDataURL('image/png');
        const link = document.createElement('a');
        link.download = `sloaner-whiteboard-page-${currentPageIndex + 1}.png`;
        link.href = dataURL;
        link.click();
    }
    
    // 保存绘图状态
    function saveDrawingState() {
        const currentPage = pages[currentPageIndex];
        
        // 删除当前步骤之后的所有历史
        currentPage.drawingHistory = currentPage.drawingHistory.slice(0, currentPage.currentStep + 1);
        
        // 添加当前绘图状态到历史
        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        currentPage.drawingHistory.push(imageData);
        
        // 更新当前步骤
        currentPage.currentStep = currentPage.drawingHistory.length - 1;
    }
    
    // 重绘画布
    function redraw() {
        const currentPage = pages[currentPageIndex];
        if (currentPage && currentPage.currentStep >= 0) {
            ctx.putImageData(currentPage.drawingHistory[currentPage.currentStep], 0, 0);
        }
    }
    
    // 获取鼠标或触摸位置
    function getPosition(e) {
        let x, y;
        
        if (e.type.includes('touch')) {
            x = e.touches[0].clientX - canvas.getBoundingClientRect().left;
            y = e.touches[0].clientY - canvas.getBoundingClientRect().top;
        } else {
            x = e.offsetX;
            y = e.offsetY;
        }
        
        return { x, y };
    }
    
    // 触摸事件处理
    function handleTouchStart(e) {
        e.preventDefault();
        startDrawing(e);
    }
    
    function handleTouchMove(e) {
        e.preventDefault();
        draw(e);
    }
    
    // 初始化页面信息
    updatePageInfo();
}); 